package com.tools_s7.net;

import com.google.gson.Gson;
import com.tools.s7.network.exception.ERROR;
import com.tools.s7.network.listener.OnRequestListener;
import com.tools.s7.network.support.BaseObserver;
import com.tools.s7.type.typeimpl.ParameterizedTypeImpl;
import com.tools.s7.utils.StringUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.ResponseBody;

public class NetObserver<T> extends BaseObserver {

    public NetObserver() {
        super();
    }

    public NetObserver(OnRequestListener<T> listener) {
        super(listener);
    }

    @Override
    protected void onResponseBody(ResponseBody body) {
        try {
            String data = body.string();
            StringUtils.showLog("请求结果", data);

            Type actualType;
            // 判断T的类型是不是List类型
            if (!(type instanceof Class)) {
//                 生成List<T> 中的 T
                Type listType = new ParameterizedTypeImpl(List.class, new Type[]{(
                        (ParameterizedType)type).getActualTypeArguments()[0]});
                // 根据List<T>生成完整的Result<List<T>>
                actualType = new ParameterizedTypeImpl(Result.class, new Type[]{listType});
            } else {
                actualType = new ParameterizedTypeImpl(Result.class, new Type[]{type});
            }
            onSuccess((( Result<T>) new Gson().fromJson(data, actualType)).getData());
        } catch (Exception e) {
            e.printStackTrace();
           onUnusual(ERROR.PARSE_ERROR, "解析错误");
        }
    }
}
